<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="140px"
      v-loading="formLoading"
    >
      <el-form-item :label="t('su.product.property')" prop="property">
        <el-table :data="propertyData">
          <el-table-column label="Code" align="center" prop="code">
            <template #default="scope">
              <el-select v-model="scope.row.code" :placeholder="t('common.inputText') + t('su.product.property')">
                <el-option
                  v-for="property in propertyList"
                  :key="property.id"
                  :label="property.name"
                  :value="property.id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="Value" align="center" prop="value">
            <template #default="scope">
              <el-input v-model="scope.row.value" :placeholder="t('common.inputText')" />
            </template>
          </el-table-column>
          <el-table-column label="Operation" align="center">
            <template #default="scope">
              <el-button type="danger" @click="delProperty(scope.$index)">{{ t('form.delete') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          style="width: 100%"
          plain
          @click="addProperty"
        >
          <Icon icon="ep:plus" class="mr-5px" /> {{ t('action.add') }}
        </el-button>
      </el-form-item>
      <el-form-item :label="t('su.product.salePrice')+'($)'" prop="salePriceUs">
        <el-input v-model="formData.salePriceUs" :placeholder="t('common.inputText') + t('su.product.salePrice')+'($)'" />
      </el-form-item>
      <el-form-item :label="t('su.product.salePrice')+'(¥)'" prop="salePriceRmb">
        <el-input v-model="formData.salePriceRmb" :placeholder="t('common.inputText') + t('su.product.salePrice')+'(¥)'" />
      </el-form-item>
      <el-form-item :label="t('su.product.purchasePrice') +'($)'" prop="purchasePriceUs">
        <el-input v-model="formData.purchasePriceUs" :placeholder="t('common.inputText') + t('su.product.purchasePrice') +'($)'" />
      </el-form-item>
      <el-form-item :label="t('su.product.purchasePrice') +'(¥)'" prop="purchasePriceRmb">
        <el-input v-model="formData.purchasePriceRmb" :placeholder="t('common.inputText') + t('su.product.purchasePrice') +'(¥)'" />
      </el-form-item>
      <el-form-item :label="t('su.product.keyword')" prop="keyword">
        <el-input v-model="formData.keyword" :placeholder="t('common.inputText') + t('su.product.keyword')" />
      </el-form-item>
      <el-form-item label="Stock" prop="stock">
        <el-input v-model="formData.stock" placeholder="Input stock" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">{{ t('common.ok') }}</el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ProductSkuApi, ProductSkuVO } from '@/api/su/productsku'
import {DICT_TYPE, getIntDictOptions} from "@/utils/dict";
import {CommonApi} from "@/api/su/common";

/** 商品sku 表单 */
defineOptions({ name: 'ProductStockSkuForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  productId: undefined,
  picUrl: undefined,
  property: undefined,
  salePriceUs: undefined,
  salePriceRmb: undefined,
  purchasePriceUs: undefined,
  purchasePriceRmb: undefined,
  keyword: undefined,
  categoryId: undefined,
  brandId: undefined,
  unit: undefined,
  stock: undefined,
})
const propertyList = ref([])
const getPropertyList = async () => {
  propertyList.value = await CommonApi.getPropertyList()
}
const propertyData = ref([])

const addProperty = async() => {
  const pro = {
    code: undefined,
    value: undefined,
  }
  propertyData.value.push(pro)
}

const delProperty = async (index) => {
  propertyData.value.splice(index, 1);
}

const formRules = reactive({
  // salePriceUs: [{ required: true, message: t('su.product.salePrice')+'($)'+t('validate.notempty'), trigger: 'blur' }],
  // salePriceRmb: [{ required: true, message: t('su.product.salePrice')+'(¥)'+t('validate.notempty'), trigger: 'blur' }],
  // purchasePriceUs: [{ required: true, message: t('su.product.purchasePrice') +'($)'+t('validate.notempty'), trigger: 'blur' }],
  // purchasePriceRmb: [{ required: true, message: t('su.product.purchasePrice') +'(¥)'+t('validate.notempty'), trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number, productId?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (productId) {
    formData.value.productId = productId
  }
  getPropertyList()
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ProductSkuApi.getProductSku(id)
      propertyData.value = JSON.parse(formData.value.property);
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    formData.value.property = JSON.stringify(propertyData.value)
    const data = formData.value as unknown as ProductSkuVO
    if (formType.value === 'create') {
      await ProductSkuApi.createProductSku(data)
      message.success(t('common.createSuccess'))
    } else {
      await ProductSkuApi.updateProductSku(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    productId: undefined,
    picUrl: undefined,
    property: undefined,
    salePriceUs: undefined,
    salePriceRmb: undefined,
    purchasePriceUs: undefined,
    purchasePriceRmb: undefined,
    keyword: undefined,
    categoryId: undefined,
    brandId: undefined,
    unit: undefined
  }
  propertyData.value = []
  formRef.value?.resetFields()
}
</script>
